package com.kaibes.module.account;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.kaibes.core.spring.proxy.Proxy;
import com.kaibes.module.account.core.AccountRes;
import com.kaibes.module.account.core.AccountService;
import com.kaibes.module.account.core.MailService;
import com.kaibes.module.account.pojo.AccountReset;
import com.kaibes.module.user.safe.UserEmail;
import com.kaibes.module.user.safe.UserSafe;
import com.kaibes.module.user.safe.UserSafeService;
import com.kaibes.web.api.ApiLink;
import com.kaibes.web.response.ResponseFactory;

@RestController
@RequestMapping("/accounts/emails")
public class AccountEmailApi {

    @Proxy(false)
    private MailService mailService;
    @Autowired
    private UserSafeService userSafeService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/reset")
    @ApiLink(value = "获取邮箱验证码", validated = false)
    public ResponseEntity<Object> resetCode(HttpSession session, @RequestBody @Validated UserEmail userEmail) {
    	if (mailService == null) {
    		return ResponseFactory.postFailure("操作失败，网站未启用邮箱模块，请联系网站管理员");
    	}
    	
        String email = userEmail.getEmail();
        UserSafe userSafe = userSafeService.getUserIdByEmail(email);
        if (userSafe == null) {
            return ResponseFactory.postFailure("该邮箱不存在，请检查是否输入了错误的邮箱！");
        }

        String emailCode = UUID.randomUUID().toString();
        session.setAttribute(AccountRes.EMAIL, email);
        session.setAttribute(AccountRes.RESET_PASSWORD_CODE, emailCode);

        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put(AccountRes.RESET_PASSWORD_CODE, emailCode);

        if (mailService.sendTemplateMessage(email, AccountRes.RESET_PASSWORD_TEMPLATE, dataModel)) {
            return ResponseFactory.ok("已发送一个验证码到您的邮箱，重复获取会导致前一个验证码失效");
        } else {
            return ResponseFactory.postFailure("操作失败，可能是网站未正确设置邮件模块，请联系网站管理员");
        }
    }

    @PutMapping("/reset")
    @ApiLink(value = "重置密码", validated = false)
    public ResponseEntity<Object> resetPassword(HttpSession session,
            @RequestBody @Validated AccountReset accountReset) {
        String email = (String) session.getAttribute(AccountRes.EMAIL);
        String emailCode = (String) session.getAttribute(AccountRes.RESET_PASSWORD_CODE);
        if (email == null || emailCode == null) {
            return ResponseFactory.putFailure("邮箱不存在或验证码已失效");
        }
        if (!emailCode.equals(accountReset.getCode())) {
            return ResponseFactory.putFailure("验证码错误或者已失效");
        }
        session.removeAttribute(AccountRes.EMAIL);
        session.removeAttribute(AccountRes.RESET_PASSWORD_CODE);
        return ResponseFactory.put(
                accountService.updatePasswordByEmail(passwordEncoder.encode(accountReset.getPassword()), email),
                "用户密码重置成功", "用户密码重置失败");
    }

}
